package cn.woochen.comlib.adapter

import android.util.SparseIntArray
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.entity.MultiItemEntity
import com.chad.library.adapter.base.viewholder.BaseViewHolder

/**
 * 如果使用Databinding绑定数据继承这个基类，
 * @author woochen
 * 使用官方推荐的BaseDataBindingHolder方式来实现存在bug(View is not a binding layout)
 */
abstract class BaseMultiItemAdapter<T : MultiItemEntity>(
    data: MutableList<T>? = null) : BaseQuickAdapter<T, BaseMultiItemAdapter.ViewHolder>(0, data) {

    private val layouts: SparseIntArray by lazy(LazyThreadSafetyMode.NONE) { SparseIntArray() }

    override fun getDefItemViewType(position: Int): Int {
        return data[position].itemType
    }

    override fun onCreateDefViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val layoutResId = layouts.get(viewType)
        val binding = DataBindingUtil.inflate<ViewDataBinding>(LayoutInflater.from(parent.context), layoutResId, parent, false)
        val viewHolder = ViewHolder(binding.root)
        viewHolder.setViewDataBinding(binding)
        return viewHolder
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        super.onBindViewHolder(holder, position)
        holder.getDataBinding<ViewDataBinding?>()?.executePendingBindings()
    }

    class ViewHolder(view: View) : BaseViewHolder(view) {
        private var mBinding: ViewDataBinding? = null
        fun setViewDataBinding(binding: ViewDataBinding) {
            mBinding = binding
        }

        fun <DB : ViewDataBinding?> getDataBinding() = mBinding as DB
    }

    /**
     * 调用此方法，设置多布局
     * @param type Int
     * @param layoutResId Int
     */
    protected fun addItemType(type: Int, @LayoutRes layoutResId: Int) {
        layouts.put(type, layoutResId)
    }
}